import type { ApiResponse } from '../types';

class ApiConfig {
    static getHeaders() {
        return {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${localStorage.getItem('token')}`,
        }
    }

    static async errorHandler(response: Response) {
        const data = await response.json();
        if (!response.ok) {
            if ([3, 4, 5].includes(data.code)) {
                window.location.href = '/login';
            }
            throw new Error(data.message);
        }


        return data;
    }

    static async get<T>(url: string): Promise<ApiResponse<T>> {
        const response = await fetch(url, {
            method: 'GET',
            headers: this.getHeaders(),
        });
        return this.errorHandler(response);
    }

    static async post<T, R>(url: string, body: T): Promise<ApiResponse<R>> {
        const response = await fetch(url, {
            method: 'POST',
            headers: this.getHeaders(),
            body: JSON.stringify(body),
        });
        return this.errorHandler(response);
    }

    static async put<T, R>(url: string, body: T): Promise<ApiResponse<R>> {
        const response = await fetch(url, {
            method: 'PUT',
            headers: this.getHeaders(),
            body: JSON.stringify(body),
        });
        return this.errorHandler(response);
    }

    static async delete<T, R>(url: string, body?: T): Promise<ApiResponse<R>> {

        const response = await fetch(url, {
            method: 'DELETE',
            headers: this.getHeaders(),
            ...(body && {
                body: JSON.stringify(body),
            }),
        });
        return this.errorHandler(response);
    }
}

export default ApiConfig